package com.jsl.action;

import com.api.system.language.autoTranslate.MD5;
import com.google.gson.Gson;
import net.sf.json.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.util.*;

public class DaibanAction2 {

    private Log log = LogFactory.getLog(DaibanAction.class);

    private String appSecret = "appSecret";
    private String appId = "appId";
    private String url = "https://www.fjjslds.com";
    private String CODE = "S20250606001";
    private String DATA_CONTENT = "我在测试";
    private String PIID = "336323"; //流程实例ID
    private String LABEL = "测试标签";// 流程编号
    private String BUSI_NAME = "[OA]库存调整单";
    private String DOC_TITLE = "库存调整单-2025-07-11"; // 业务标题（流程标题）
    private String DEFINE_ID = "BIZ" + Math.round(Math.random() * 100000); // 流程 ID（业务 ID）
    private boolean IS_START = true; // 是否开始
    private boolean IS_END = false; // 是否结束
    private String APPLY_NAME = "邢蕾"; // 申请人名称
    private String APPLY_CODE = "8f407a9eaf9241aba69eef1d19c94127"; // 申请人编码
    private String APPLY_TIME = "2025-08-01T12:00:00"; // 创建时间，格式如 "2023-10-01T12:00:00"
    private String PASS_TASK_ID = "YIBAN" + Math.round(Math.random() * 100000); // 已办待办 ID
    // 新增常量
    private String PASS_ACTV_NAME = "测试环节"; // 已办环节名称
    private String PASS_USER_CODE = "8f407a9eaf9241aba69eef1d19c94127"; // 已办人员编号
    private String PASS_USER_NAME = "已办人员名称"; // 已办人员名称
    private String REMARK = "your_remark_value"; // 备注
    private String NOTE = "your_note_value"; // 信息说明
    private String OPR_TYPE = "submit"; // 操作类型，可选值：stateRecall、closeprocess、revoke、forceEnd
    private String ASSIGN_ARRAY = buildArray(); // 指派信息数组，具体内容结构需根据实际需求填充
    private String LINK_URL_IM = "https://www.jd.com"; // 移动端链接
    private String LINK_URL_PC = "https://oa.hbjinshenglan.com/spa/workflow/4form/index.html?#/main/workflow/req?requestid=336323"; // PC端链接
    private String CATEGORY_ID = "dd00d4fa686f4f03936b968cb4402d62"; // 分类ID
    private String SYSTEM_CODE = "your_system_code_value"; // 系统编号
    private String SYSTEM_NAME = "your_system_name_value"; // 系统名称

    public void main(String[] args) {
        System.out.println("开始推送金盛兰云台");
    }

    /**
     * 签名生成函数
     *
     * @param map
     * @param allrowEmpty
     * @return
     */
    public String mapSortToUrlParam(Map<String, String> map, Boolean allrowEmpty) {
        List<String> keys = new ArrayList<>(map.keySet());
        Collections.sort(keys, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                // 返回相反的compare
                return o1.compareTo(o2);
            }
        });
        Iterator<String> iter = keys.iterator();
        StringBuffer signStr = new StringBuffer();
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = map.get(key);
            if (!allrowEmpty && value == null) {// 不允许值为空
                continue;
            }
            if (signStr.length() > 0) {
                signStr.append("&");
            }
            signStr.append(key).append("=").append(value);
        }
        //System.out.println(signStr.toString());
        return signStr.toString();
    }

    /**
     * <p>Title: postForm</p>
     * <p>Description: 请求</p>
     *
     * @param url
     * @param headMap
     * @param params
     * @return
     * @throws Exception
     */
    public String postForm(String url, Map<String, Object> headMap, Map<String, String> params) throws Exception {
        try {
            // post请求
            HttpPost httpPost = new HttpPost(url);
            if (headMap != null && !headMap.isEmpty()) {// 头部
                for (String key : headMap.keySet()) {
                    httpPost.setHeader(key, headMap.get(key) != null ? headMap.get(key).toString() : "");
                }
            }
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    nvps.add(new BasicNameValuePair(key, params.get(key) != null ? params.get(key).toString() : ""));
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(nvps, "utf-8"));
            int socketTimeout = 30000;
            int connectionTimeout = 30000;
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout)
                    .setConnectTimeout(connectionTimeout).build();// 设置请求和传输超时时间
            httpPost.setConfig(requestConfig);
            // 发送请求
            HttpClient httpclient = null;
            httpclient = HttpClientBuilder.create().build();
            HttpResponse httpresponse = httpclient.execute(httpPost);
            // 获取返回数据
            HttpEntity entity = httpresponse.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            return body;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
    }

    private void sendRequest() throws Exception {
        long timestamp = new Date().getTime();
        //生成签名的参数
        Map<String, String> param1 = new HashMap<String, String>();
        param1.put("appId", appId);
        param1.put("appSecret", appSecret);
        param1.put("timestamp", String.valueOf(timestamp));
        String param1str = mapSortToUrlParam(param1, true);
        String sign = MD5.md5(param1str);
        Map<String, String> param = new HashMap<String, String>();
        param.put("appId", appId);
        param.put("timestamp", String.valueOf(timestamp));
        param.put("sign", sign);
        //获取token
        String url1 = url + "/spiToken";
        String tokenresult = postForm(url1, null, param);
        System.out.println("token:" + tokenresult);
        //解析结果中token[结果要判断，这里只是做个样例]
        JSONObject jsonObject = JSONObject.fromObject(tokenresult);
        //[结果要判断，这里只是做个样例]
        String token = jsonObject.getString("data");
        System.out.println("token:" + token);

        //调用spi接口
        String url2 = url + "/intf";

        //生成签名的参数
        Map<String, String> signParams = buildSignParams(appSecret, timestamp);
        String sign2 = MD5.md5(mapSortToUrlParam(signParams, true));

        Map<String, String> requestParams = buildRequestParams(timestamp, sign2);
        System.out.println(requestParams);

        Map<String, Object> head = buildHeaders(token);
        System.out.println(requestParams);
        String result = postForm(url2, head, requestParams);
        System.out.println(result);
    }

    /**
     * 构造签名参数
     *
     * @param appSecret
     * @param timestamp
     * @return
     */
    private Map<String, String> buildSignParams(String appSecret, long timestamp) {
        Map<String, String> params = new HashMap<>();
        params.put("code", CODE);
        params.put("appSecret", appSecret);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("data", DATA_CONTENT);
        params.put("piid", PIID);
        params.put("label", LABEL);
        params.put("busiName", BUSI_NAME);

        params.put("docTitle", DOC_TITLE); // 业务标题（流程标题）
        params.put("defineId", DEFINE_ID); // 流程 ID（业务 ID）
        params.put("isStart", String.valueOf(IS_START)); // 是否开始
        params.put("isEnd", String.valueOf(IS_END)); // 是否结束
        params.put("applyName", APPLY_NAME); // 申请人名称
        params.put("applyCode", APPLY_CODE); // 申请人编码
        params.put("applyTime", APPLY_TIME); // 创建时间
        params.put("passTaskId", PASS_TASK_ID); // 已办待办 ID

        params.put("passActvName", PASS_ACTV_NAME); // 已办环节名称
        params.put("passUserCode", PASS_USER_CODE); // 已办人员编号
        params.put("passUserName", PASS_USER_NAME); // 已办人员名称
        params.put("remark", REMARK); // 备注
        params.put("note", NOTE); // 信息说明
        params.put("oprType", OPR_TYPE); // 操作类型
        params.put("assignArray", ASSIGN_ARRAY); // 指派信息
        params.put("linkUrlIm", LINK_URL_IM); // 移动端链接
        params.put("linkUrlPc", LINK_URL_PC); // PC端链接
        params.put("categoryId", CATEGORY_ID); // 分类ID
        params.put("systemCode", SYSTEM_CODE); // 系统编号
        params.put("systemName", SYSTEM_NAME); // 系统名称
        return params;
    }

    private Map<String, String> buildRequestParams(long timestamp, String sign) {
        Map<String, String> params = new HashMap<>();
        params.put("code", CODE);
        params.put("timestamp", String.valueOf(timestamp));
        params.put("sign", sign);
        params.put("data", DATA_CONTENT);
        params.put("piid", PIID);
        params.put("label", LABEL);
        params.put("busiName", BUSI_NAME);
        params.put("docTitle", DOC_TITLE); // 业务标题（流程标题）
        params.put("defineId", DEFINE_ID); // 流程 ID（业务 ID）
        params.put("isStart", String.valueOf(IS_START)); // 是否开始
        params.put("isEnd", String.valueOf(IS_END)); // 是否结束
        params.put("applyName", APPLY_NAME); // 申请人名称
        params.put("applyCode", APPLY_CODE); // 申请人编码
        params.put("applyTime", APPLY_TIME); // 创建时间
        params.put("passTaskId", PASS_TASK_ID); // 已办待办 ID

        params.put("passActvName", PASS_ACTV_NAME); // 已办环节名称
        params.put("passUserCode", PASS_USER_CODE); // 已办人员编号
        params.put("passUserName", PASS_USER_NAME); // 已办人员名称
        params.put("remark", REMARK); // 备注
        params.put("note", NOTE); // 信息说明
        params.put("oprType", OPR_TYPE); // 操作类型
        params.put("assignArray", ASSIGN_ARRAY); // 指派信息
        params.put("linkUrlIm", LINK_URL_IM); // 移动端链接
        params.put("linkUrlPc", LINK_URL_PC); // PC端链接
        params.put("categoryId", CATEGORY_ID); // 分类ID
        params.put("systemCode", SYSTEM_CODE); // 系统编号
        params.put("systemName", SYSTEM_NAME); // 系统名称
        return params;
    }

    private Map<String, Object> buildHeaders(String token) {
        Map<String, Object> headers = new HashMap<>();
        headers.put("access_token", token);
        return headers;
    }

    private String buildArray() {
        List<Map<String, Object>> assignArray = new ArrayList<>();

        // 示例数据
        String[] actvNames = {"审批测试环节1"};
        String[] taskIds = {"TASK" + Math.round(Math.random() * 100000)};
        String[] userCodes = {"da7e1da96f5a459891dfd45ddee4f3a0"};
        String[] userNames = {"用户名称"};
        int msgInfoType = 2; // 待办

        for (int i = 0; i < actvNames.length; i++) {
            Map<String, Object> assignItem = new HashMap<>();
            assignItem.put("actvName", actvNames[i]);
            assignItem.put("taskId", taskIds[i]);
            assignItem.put("userCode", userCodes[i]);
            assignItem.put("userName", userNames[i]);
            assignItem.put("msgInfoType", msgInfoType);

            // 可选字段
            assignItem.put("remark", ""); // 如果有备注，替换为空字符串
            assignItem.put("note", "");   // 如果有注释信息，替换为空字符串

            assignArray.add(assignItem);
        }

        // 使用Gson将列表转换为JSON字符串
        Gson gson = new Gson();
        String jsonString = gson.toJson(assignArray);

        return jsonString;
    }


}
